package lambda.collector;

import org.junit.Test;

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.*;

/**
 * Created by yl on 2019/10/12
 */
public class CollectorsSupplied {

    @Test
    public void toListtest(){
        String arr[] = {"a","b","c","d","e"};
        List<String> list = Arrays.stream(arr).collect(Collectors.toList());
        list.forEach(x -> System.out.println(x));
    }

    @Test
    public void toCollcetiontest(){
        String arr[] = {"a","b","c","d","e"};
        List<String> list = Arrays.stream(arr).collect(Collectors.toCollection(ArrayList::new));
        list.forEach(x -> System.out.println(x));
    }

    //可排重
    @Test
    public void toSettest(){
        String arr[] = {"a","b","b","c","c"};
        Set<String> set = Arrays.stream(arr).collect(Collectors.toCollection(HashSet::new));
        set.forEach(x -> System.out.println(x));
    }


    //toSet默认是返回HashSet，如果需要返回TreeSet，直接用CollectorImpl
    @Test
    public void toTreeSet_test(){
        String arr[] = {"a","b","b","c","c"};
        TreeSet<String> set  = Arrays.stream(arr).parallel().collect(Collectors.toCollection(TreeSet::new));
        set.forEach(x -> System.out.println(x));
    }

    @Test
    public void stringJoin_test() {
        String arr[] = {"a", "b", "b", "c", "c"};
       String result =  Arrays.stream(arr).parallel().collect(Collectors.joining());
        System.out.println(result);
    }

    @Test
    public void stringJoinDeleter_test() {
        String arr[] = {"a", "b", "b", "c", "c"};
        String result =  Arrays.stream(arr).parallel().collect(Collectors.joining("/","_","_"));
        System.out.println(result);
    }

    @Test
    public void parallelSum_test(){
        Arrays.asList(1,2,3,4,5).stream().parallel().collect(Collectors.summingInt(value -> value));
    }

    @Test
    public void mapping_test(){
        int i = 5000000;
        People peoples[] = new People[i];
        for (int j = 0; j < i; j++) {
            People people = new People(j % 5 < 2 ? new City("beijing"):new City("上海"),"zhangsan+"+j);
            peoples[j] = people;
        }
        long now = System.currentTimeMillis();
        Map<City, Set<String>> lastNamesByCity
                = Arrays.stream(peoples).parallel().collect(groupingBy(People::getCity,
                mapping(People::getLastName, toSet())));

        /*lastNamesByCity.forEach((city,setname) -> {
            System.out.println(city + ":" + setname.stream().collect(Collectors.joining(",")));
        });*/

        lastNamesByCity.forEach((city,setname) -> {
            System.out.println(city + ":" + setname.stream().collect(Collectors.counting()));
        });
        System.out.println("spend : "+(System.currentTimeMillis() - now));
    }
    //mapping用来将一个类型转换为另外一个类型，groupingBy需要一个collector来生成map的key和value，而它能得到的类型是People，
    //这个时候用来转化是有用的，但是它没有提供额外的计算能力




}
